<template>
  <div class="operation-log-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>操作日志</span>
        </div>
      </template>
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="请求路径">
          <el-input v-model="queryForm.path" placeholder="请输入请求路径" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="queryForm.start_time"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="queryForm.end_time"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            v-permission="'operation_logs.delete'"
            type="danger"
            @click="handleClear"
          >
            清空日志
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="description" label="操作说明" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.description || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="method" label="请求方法" width="100" />
        <el-table-column prop="path" label="请求路径" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
              {{ row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-permission="'operation_logs.view'"
              type="primary"
              link
              @click="handleView(row)"
            >
              详情
            </el-button>
            <el-button
              v-permission="'operation_logs.delete'"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="操作日志详情" width="800px">
      <el-descriptions :column="2" border v-if="detailData">
        <el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ detailData.username }}</el-descriptions-item>
        <el-descriptions-item label="操作说明" :span="2">
          <span style="font-weight: 500; color: #409EFF;">{{ detailData.description || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag type="info">{{ detailData.action || '-' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="资源类型">
          <el-tag type="warning">{{ detailData.resource || '-' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">
          <el-tag :type="detailData.method === 'GET' ? 'success' : 'primary'">
            {{ detailData.method }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求路径">{{ detailData.path }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ detailData.ip }}</el-descriptions-item>
        <el-descriptions-item label="User-Agent" :span="2">{{ detailData.user_agent }}</el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2" v-if="detailData.params">
          <pre style="max-height: 200px; overflow-y: auto; background: #f5f5f5; padding: 10px; border-radius: 4px;">{{ JSON.stringify(detailData.params, null, 2) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="变更前数据" :span="2" v-if="detailData.before_data">
          <pre style="max-height: 200px; overflow-y: auto; background: #fff3cd; padding: 10px; border-radius: 4px;">{{ JSON.stringify(detailData.before_data, null, 2) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="变更后数据" :span="2" v-if="detailData.after_data">
          <pre style="max-height: 200px; overflow-y: auto; background: #d1ecf1; padding: 10px; border-radius: 4px;">{{ JSON.stringify(detailData.after_data, null, 2) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="变更字段" :span="2" v-if="detailData.changes">
          <pre style="max-height: 200px; overflow-y: auto; background: #f8d7da; padding: 10px; border-radius: 4px;">{{ JSON.stringify(detailData.changes, null, 2) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="响应结果" :span="2" v-if="detailData.response">
          <pre style="max-height: 200px; overflow-y: auto; background: #f5f5f5; padding: 10px; border-radius: 4px;">{{ JSON.stringify(detailData.response, null, 2) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailData.status === 'success' ? 'success' : 'danger'">
            {{ detailData.status === 'success' ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ formatDateTime(detailData.created_at) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/date'

const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const detailData = ref(null)

const queryForm = reactive({
  username: '',
  path: '',
  status: '',
  start_time: '',
  end_time: '',
})

const pagination = reactive({
  page: 1,
  pageSize: 15,
  total: 0,
})

const fetchData = async () => {
  loading.value = true
  try {
    const response = await request.get('/operation-logs', {
      params: {
        ...queryForm,
        page: pagination.page,
        page_size: pagination.pageSize,
      },
    })
    if (response.code === 200) {
      tableData.value = response.data.data
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(queryForm, {
    username: '',
    path: '',
    status: '',
    start_time: '',
    end_time: '',
  })
  handleQuery()
}

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有操作日志吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const response = await request.delete('/operation-logs/clear/all')
    if (response.code === 200) {
      ElMessage.success('清空成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '清空失败')
    }
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const response = await request.get(`/operation-logs/${row.id}`)
    if (response.code === 200) {
      detailData.value = response.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取日志详情失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const response = await request.delete(`/operation-logs/${row.id}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除日志失败:', error)
    }
  }
}

const handleSizeChange = () => {
  fetchData()
}

const handlePageChange = () => {
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.operation-log-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
  }

  .search-form {
    margin-bottom: 20px;
  }
}
</style>

